package com.ei.itop.common.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ailk.dazzle.util.AppContext;
import com.ailk.dazzle.util.sec.Encrypt;
import com.ailk.dazzle.util.type.StringUtils;
import com.ei.itop.common.constants.SysConstants;
import com.ei.itop.common.dbentity.CcUser;
import com.ei.itop.common.dbentity.ScOp;
import com.ei.itop.common.dbentity.ScOrg;
import com.ei.itop.login.bean.LoginInfo;
import com.ei.itop.login.service.LoginService;
import com.ei.itop.scmgnt.service.ScOrgService;

public class LoginFilter implements Filter{

	public void init(FilterConfig filterConfig) throws ServletException {}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hrs = (HttpServletRequest)request;
		HttpServletResponse hrq = (HttpServletResponse)response;
		if(hrs.getSession().getAttribute(SysConstants.SessionAttribute.OP_SESSION)==null&&!isStaticResource(hrs.getRequestURL().toString())){
			Cookie loginCookie = CookieUtil.getCookie(hrs.getCookies(), SysConstants.CookieAttribute.LOGIN_KEY);
			boolean lResult = false;
			if(loginCookie!=null){
				lResult = doLogin(hrs, hrq);
				if(lResult){
					chain.doFilter(request, response);
				}else{
					hrq.sendRedirect(hrs.getContextPath()+"/login.jsp?fromURL="+hrs.getRequestURL());
				}
			}else{
				hrq.sendRedirect(hrs.getContextPath()+"/login.jsp?fromURL="+hrs.getRequestURL());
			}
		}else{
			chain.doFilter(request, response);
		}
	}
	
	
	public boolean isStaticResource(String url){
		String suffix = url.substring(url.lastIndexOf(".")+1,url.length());
		if("js".equals(suffix)){
			return true;
		}
		return false;
	}
	
	public boolean doLogin(HttpServletRequest request,HttpServletResponse response){
		Cookie loginCookie = CookieUtil.getCookie(request.getCookies(), SysConstants.CookieAttribute.LOGIN_KEY);
		if(loginCookie==null||StringUtils.isEmpty(loginCookie.getValue())){
			return false;
		}
		String[] loginInfo = Encrypt.decrypt(loginCookie.getValue()).split(SysConstants.CookieAttribute.LOGIN_KEY_SEP);
		// 获取登录的操作员类型
		String opType = loginInfo[0];
		// 用户名
		String accountNo = loginInfo[1];
		// 密码
		String accountPwd = loginInfo[2];
		// 封装登录Bean
		LoginInfo li = new LoginInfo();
		li.setLoginCode(accountNo.toLowerCase());
		li.setLoginPasswd(accountPwd);
		// 如果是用户登录
		if (SysConstants.OpAttribute.OP_ROLE_USER.equals(opType)) {
			CcUser user = null;
			try {
				user = ((LoginService)AppContext.getBean(LoginService.class)).userLogin(li);
			} catch (Exception e) {
				return false;
			}
			// 账号密码不正确
			if (user == null) {
				return false;
			} else {
				LoginUtil.putLoginInfo2Session(request, response, accountNo,
						user.getCcUserId(), user.getLoginCode(),
						user.getOpName(),
						user.getLastName() + "." + user.getFirstName(),
						opType, user.getScOrgId(), user.getScOrgName(),
						user.getCcCustId(), user.getOpKind(),accountPwd,null);
				return true;
			}
		}
		// 如果是服务方登录
		else if (SysConstants.OpAttribute.OP_ROLE_OP.equals(opType)) {
			ScOp op = null;
			try {
				op = ((LoginService)AppContext.getBean(LoginService.class)).adviserLogin(li);
			} catch (Exception e) {
				return false;
			} 
			// 账号密码不正确
			if (op == null) {
				return false;
			} else {
				//获取组织名称
				ScOrg scOrg = null;
				try {
					scOrg = ((ScOrgService)AppContext.getBean(ScOrgService.class)).queryScOrg(op.getScOrgId());
				} catch (Exception e) {
					return false;
				}
				//放入Session
				LoginUtil.putLoginInfo2Session(request, response, accountNo,
						op.getScOpId(), op.getLoginCode(), op.getOpName(),
						op.getLastName() + "." + op.getFirstName(), opType,
						op.getScOrgId(), scOrg.getScOrgName(), null, op.getOpKind().longValue(),accountPwd,null);
				return true;
			}
		}
		return false;
	}
	

	public void destroy() {
		
	}
	
}
